package top.codedance.iotp.client.plugins.sync.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.client.ClientApplication;
import top.codedance.iotp.common.executer.SyncAbstractExecuter;
import top.codedance.iotp.common.entity.PluginResultEntity;
import org.apache.log4j.Logger;

import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;

public class ShutdownExecuterImpl extends SyncAbstractExecuter {
    private static Logger logger = ClientApplication.getLogger(ShutdownExecuterImpl.class);

    @Override
    public PluginResultEntity exec(byte[] data, String taskId) {
        PluginResultEntity result = new PluginResultEntity();
        try {
            String body = new String(data, StandardCharsets.UTF_8);
            JSONObject jo = JSON.parseObject(body);
            final Boolean isExceptionExit = jo.getBoolean("isExceptionExit");
            int amount;
            if(jo.containsKey("amount")){
                amount = jo.getIntValue("amount");
                if(amount < 1){
                    amount = 1;
                }
            }else{
                amount = 10;
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.SECOND, amount);
            ClientApplication.timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    logger.debug("user shutdown.");
                    System.exit(isExceptionExit?1:0);
                }
            }, calendar.getTime());
            result.setOk(true);
            result.setContext("Client will shutdown in " + amount + " seconds.");
        }catch (Exception ex){
            result.setOk(false);
            result.setMsg(ex.getMessage());
        }
        return result;
    }
}